var express = require('express');
var router = express.Router();
var cache = require ('memory-cache') ;
var handlebars = require('handlebars'); 
var path = require('path');
var SqliteDB = require('sqlite3').verbose();


/* GET users listing. */
router.get('/', function(req, res, next) {
  var smDict = cache.get('smDict');
  var params = req.query;
  if(!(req.session && req.session['username']) || !params['sm']){
    //setTimeout(() => {
      res.redirect('./index.html');
    //}, 5000);    
    //res.send(JSON.stringify({flag:1, val:"非法请求！"}));
    return;
  }
  try{
    var sm = smDict[params['sm']];
    var sql = handlebars.compile(sm.sql)(params); 

    var db = new SqliteDB.Database(path.join(__dirname + '/../db/aiattendance.s3db'));
    var re = {flag: 0};
    db.serialize(function(){
      db.get(sql, function(){
        if(arguments.length>=2){      
          re['val'] = arguments[1];
        }
        res.send(JSON.stringify(re));
      })
    });  
    db.close();
  }catch(err){
    res.send(JSON.stringify({flag:1, val: err}));
  }
});


module.exports = router;
